package com.base.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.base.domain.SysDept;
import com.base.enums.DeletedEnum;
import com.base.mapper.SysDeptMapper;
import com.base.service.SysDeptService;
import com.base.utils.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author gxd
 * @since 2025/6/6
 */
@Slf4j
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {

    /**
     * 分页列表-部门列表
     * @param dept 部门查询条件
     * @return 部门列表
     */
    @Override
    public List<SysDept> pageList(SysDept dept) {
        List<SysDept> list = this.list(
                Wrappers.lambdaQuery(SysDept.class)
                        .eq(SysDept::getDeleted, DeletedEnum.NO.getCode())
                        .like(StrUtil.isNotBlank(dept.getDeptName()), SysDept::getDeptName, dept.getDeptName())
                        .eq(ObjUtil.isNotNull(dept.getStatus()), SysDept::getStatus, dept.getStatus())
                        .orderByAsc(SysDept::getParentId, SysDept::getSort)
        );
        return list;
    }

    /**
     * 添加或修改-部门信息
     * @param dept 部门实体
     * @return 部门信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public SysDept addOrEdit(SysDept dept) {
        Assert.notNull(dept, "部门信息不能为空");
        if (ObjUtil.isNotNull(dept.getId())) {
            SysDept deptInfo = Assert.notNull(this.getById(dept.getId()), "要修改的部门记录不存在");
            BeanUtils.copyNotEmptyProperties(dept, deptInfo);
            this.updateById(deptInfo);
            return deptInfo;
        }

        dept.setDeleted(DeletedEnum.NO.getCode());
        this.save(dept);
        return dept;
    }
}
